/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cjt2325.cameralibrary.listener;

import com.cjt2325.cameralibrary.JCameraView;
import com.cjt2325.cameralibrary.state.CameraMachine;
import com.cjt2325.cameralibrary.util.LogUtil;

import com.cjt2325.cameralibrary.util.ScreenUtils;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.Image;
import ohos.media.image.ImageReceiver;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageFormat;
import ohos.media.image.common.Size;

/**
 * IImageArrivalListener Impl
 */
public class IImageArrivalListenerImpl implements ImageReceiver.IImageArrivalListener {
    private CameraMachine mMachine;

    public IImageArrivalListenerImpl(CameraMachine machine) {
        this.mMachine = machine;
    }

    @Override
    public void onImageArrival(ImageReceiver receiver) {
        if (receiver == null) {
            takePictureError("ImageReceiver is null");
            return;
        }
        Image readNextImage = receiver.readNextImage();
        LogUtil.error(
                LogUtil.DEFAULT_TAG, "readLatestImage:" + readNextImage + ":LastImage:" + receiver.readLatestImage());
        if (readNextImage == null) {
            receiver.release();
            takePictureError("ImageReceiver no readNextImage");
            return;
        }
        Image.Component component = readNextImage.getComponent(ImageFormat.ComponentType.JPEG);
        if (component == null) {
            takePictureError("ImageReceiver component null");
            return;
        }
        byte[] bytes = new byte[component.remaining()];
        component.read(bytes);

        ImageSource source = ImageSource.create(component.getBuffer(), null);
        if (source == null) {
            takePictureError("ImageReceiver ImageSource null");
            return;
        }

        float maxWidth = ScreenUtils.getScreenWidth(mMachine.getContext());
        float maxHeight = ScreenUtils.getScreenHeight(mMachine.getContext());

        Size size = source.getImageInfo().size;
        int actualHeight = size.height;
        int actualWidth = size.width;
        float imgRatio = (float) actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;
        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;
            }
        }

        ImageSource.DecodingOptions options = new ImageSource.DecodingOptions();
        options.sampleSize = calculateInSampleSize(size, actualWidth, actualHeight);
        options.desiredSize = new Size(actualWidth, actualHeight);

        PixelMap pixelMap = source.createPixelmap(null);
        if (pixelMap == null) {
            takePictureError("ImageReceiver pixelMap null");
            return;
        }
        new EventHandler(EventRunner.getMainEventRunner())
                .postTask(
                        () -> {
                            mMachine.getView().showPicture(pixelMap, true);
                            mMachine.setState(mMachine.getBorrowPictureState());
                            mMachine.restart();
                        });
    }

    /**
     * @param size      Size
     * @param reqWidth  int
     * @param reqHeight int
     * @return int
     */
    private int calculateInSampleSize(Size size, int reqWidth, int reqHeight) {
        int height = size.height;
        int width = size.width;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            int halfHeight = height / 2;
            for (int halfWidth = width / 2; halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth; inSampleSize *= 2) {
            }
        }
        return inSampleSize;
    }

    private void takePictureError(String error) {
        LogUtil.error(LogUtil.DEFAULT_TAG, "takePictureError:" + error);
        new EventHandler(EventRunner.getMainEventRunner())
                .postTask(
                        () -> {
                            mMachine.getView().resetState(JCameraView.TYPE_PICTURE);
                            mMachine.setState(mMachine.getPreviewState());
                        });
    }
}
